#include "GGE_Lib.h"

void cImg::load( char *path )
{
  img = IMG_Load ( path );
}

void cImg::uload()
{
  SDL_FreeSurface ( img );
}

cEntity::cEntity( int nf )
{
  sprite = new cImg[nf];
  nFrames = nf;
  cont = 0;
}

cEntity::cEntity()
{
  int nf=1;
  sprite = new cImg[nf];
  nFrames = nf;
  cont = 0;
}

void cEntity::addframe( cImg frameImg )
{
  if (cont<nFrames)
    {
      sprite[cont]=frameImg;
      cont++;
    }
}

void cEntity::draw ( int _x, int _y )
{
  nOfColors = sprite[estado].img->format->BytesPerPixel;
  if (nOfColors == 4)
    {
      if (sprite[estado].img->format->Rmask == 0x000000ff)
        texture_format = GL_RGBA;
      else
        texture_format = GL_BGRA;
    }
  else if (nOfColors == 3)
    {
      if (sprite[estado].img->format->Rmask == 0x000000ff)
        texture_format = GL_RGB;
      else
        texture_format = GL_BGR;
    }
  else
    {
      printf("Atencion: La imagen no es de color real, puede que cause errores.\n");
    }

  glGenTextures( 1, &uiGSprite );
  glBindTexture( GL_TEXTURE_2D, uiGSprite );
  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
  glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, sprite[estado].img->w, sprite[estado].img->h, 0,
                texture_format, GL_UNSIGNED_BYTE, sprite[estado].img->pixels );
  glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);

  glLoadIdentity();
  glBindTexture( GL_TEXTURE_2D,uiGSprite );
  glColor4f( 255 , 255, 255, 1 );
  glTranslatef ( _x  ,_y  ,0 );

  glBegin( GL_QUADS );
  glTexCoord2i( 0, 0 );
  glVertex3f( x, y, 0 );
  glTexCoord2i( 1, 0 );
  glVertex3f( x + sprite[estado].img->w, y, 0 );
  glTexCoord2i( 1, 1 );
  glVertex3f( x + sprite[estado].img->w, y + sprite[estado].img->h, 0 );
  glTexCoord2i( 0, 1 );
  glVertex3f( x, y + sprite[estado].img->h, 0 );
  glEnd();
  glFinish();
  glDeleteTextures(1, &uiGSprite);
}


